package com.hx.utils;

import com.hx.entity.Student;

import java.lang.reflect.*;

/**
 * 反射应用
 */
public class MyReflect {
    public static void main(String[] args) {
//        cancelAccess();
        getMethodInfo();
    }

    public static void getMethodInfo() {
        try {
            Class<?> cls = Class.forName("com.hx.bean.Student");
            Field[] fields = cls.getFields();
            //只能获取公有的成员变量
            for (int i = 0; i < fields.length; i++) {
                System.out.println("获取到公有的成员变量：" + fields[i].getName());
            }
            System.out.println("************以下是获取方法的参数名、参数类型");
            Method[] methods = cls.getMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                if (!"add".equals(methodName)) {
                    continue;
                }
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    String name = parameters[i].getType().getName();
                    System.out.println(methodName + "的第" + (i + 1) + "个入参名为：" + parameters[i].getName() + " 参数类型为：" + name);
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void cancelAccess() {
        //通过反射创建对象
        try {
            Class studentClass = Student.class;
            Constructor c = studentClass.getConstructor(String.class, String.class, int.class);
            Object obj = c.newInstance("小明", "1001", 18);
            //通过属性名获取field对象
            Field f = studentClass.getDeclaredField("name");
            //取消属性访问权限控制
//            f.setAccessible(true);
            //获取更改前name的值
            System.out.println("更改前:" + f.get(obj));
            System.out.println(obj);
            f.set(obj, "小刚");
            System.out.println("更改后:" + f.get(obj));
            System.out.println(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
